import React, { useEffect, useState } from 'react';
import { NavigationProp, RouteProp } from '@react-navigation/native';
import { useReactive } from 'ahooks';
import { StyleSheet, Button, TouchableOpacity } from 'react-native';
import { View, Text } from 'native-base';
import Stepper from '../../../component/Stepper.tsx';
import { CommonStyle } from '../../../common/commonStyle.ts';
import HomeRequest from '../../../request/homeRequest.ts';
import Radios from '../../../component/Radios.tsx';
import { Loading } from '../../../component/LoadingOverlay.tsx';
import { useSelector } from 'react-redux';
import { AppDispatch, RootState } from '../../../redux/store.ts';

interface IPropertyPaymentProps {
  navigation: NavigationProp<any, 'propertyPayment'>;
  route: RouteProp<{ propertyPayment: any }, 'propertyPayment'>;
}

interface IActiveParams {
  beeperId: number;
  btnId: number;
}

interface IData {
  information: IGetPayInfo;
  activeParams: IActiveParams | undefined;
  activityText: null | string;
  radio: number | string;
  number: number;
  price: null | number;
  months: number | string;
}

const PropertyPayment: React.FC<IPropertyPaymentProps> = ({ navigation, route }) => {
  const beeperId = useSelector((state: RootState) => state.beeperId);
  const btnInformation = useSelector((state: RootState) => state.btnInformation); //按钮里面的数据
  const data = useReactive<IData>({ information: { address: '', houseSpace: 0, pmcLatestDate: '', pmcExpireDate: '', feePeriod: '', pmcPrice: 0, pmcSingleDiscount: 0 }, activeParams: { beeperId: beeperId, btnId: btnInformation!.id }, activityText: '', radio: 1, number: 1, price: null, months: 1 });
  const [periodList, setPeriodList] = useState([
    { name: '月', state: 1, isCheck: false, disabled: false },
    { name: '季度', state: 2, isCheck: false, disabled: false },
    { name: '年', state: 3, isCheck: false, disabled: false },
  ]);

  const getActivePreferential = (months: number) => {
    Loading.show('加载中');
    HomeRequest.GetActivePreferential({
      beeperId: data.activeParams?.beeperId,
      btnId: data.activeParams?.btnId,
      months: months,
    })
      .then((res) => {
        if (res.data) {
          data.activityText = res.data as string;
        }
        Loading.hide();
      })
      .catch((error) => {
        Loading.hide();
      });
  };

  useEffect(() => {
    Loading.show('加载中');
    let params = {
      beeperId: data.activeParams?.beeperId,
      btnId: data.activeParams?.btnId,
    };
    HomeRequest.GetPropertyPaymentInfo(params)
      .then((res) => {
        Loading.hide();
        const res_data = res.data;
        data.information = res_data;
        data.information.pmcExpireDate = data.information.pmcExpireDate.substring(0, 10);
        data.information.pmcLatestDate = data.information.pmcLatestDate.substring(0, 10);
        if (data.information?.feePeriod) {
          const feePeriod = data.information?.feePeriod;
          if (feePeriod.includes(',')) {
            const result = periodList.filter((item) => feePeriod.split(',').map(Number).includes(item.state));
            setPeriodList(result);
          } else {
            setPeriodList(periodList.slice(0, 1));
          }
        } else {
          setPeriodList([]);
        }
      })
      .catch((error) => {
        Loading.hide();
      });
    handleProcessingPrices(1);
    // getActivePreferential(1)
  }, []);

  //处理价格
  const handleProcessingPrices = (months: number) => {
    const { houseSpace, pmcPrice, pmcSingleDiscount } = data.information;
    const countPrice = houseSpace * pmcPrice * months * (pmcSingleDiscount || 1);
    data.price = countPrice;
    // console.log((Math.round((countPrice + Number.EPSILON) * 100) / 100) * 100,'aaaaaaaa')
  };

  // 月份数量处理
  const handleTextareaInput = (e: number) => {
    const { radio } = data;
    let months = 1;
    if (radio === 1) months = 1 * e;
    if (radio === 2) months = 3 * e;
    if (radio === 3) months = 12 * e;
    // getActivePreferential(months)
    handleProcessingPrices(months);
  };

  const getStepperNum = (num: number) => {
    data.number = num;
    handleTextareaInput(num);
  };

  const getRadioVal = (state: number | string) => {
    data.radio = state;
    let months = 1;
    if (data.radio === 1) months = 1;
    if (data.radio === 2) months = 3;
    if (data.radio === 3) months = 12;
    // getActivePreferential(months)
    handleProcessingPrices(months);
  };

  // 提交缴费
  const handleSubmit = () => {};

  return (
    <View>
      <View style={styles.container}>
        <View style={styles.contentBox}>
          <View style={styles.viewFlex}>
            <View style={styles.flexLeft}>
              <Text style={styles.lSize}>门牌号</Text>
            </View>
            <View style={styles.flexRight}>
              <Text style={styles.rSize}>{data.information?.address}</Text>
            </View>
          </View>
          <View style={styles.viewFlex}>
            <View style={styles.flexLeft}>
              <Text style={styles.lSize}>房屋面积</Text>
            </View>
            <View style={styles.flexRight}>
              <Text style={styles.rSize}>{data.information?.houseSpace}m²</Text>
            </View>
          </View>
          <View style={styles.viewFlex}>
            <View style={styles.flexLeft}>
              <Text style={styles.lSize}>上次缴费时间</Text>
            </View>
            <View style={styles.flexRight}>
              <Text style={styles.rSize}>{data.information?.pmcLatestDate}</Text>
            </View>
          </View>
          <View style={[styles.viewFlex, { borderBottomWidth: 0 }]}>
            <View style={styles.flexLeft}>
              <Text style={styles.lSize}>到期时间</Text>
            </View>
            <View style={styles.flexRight}>
              <Text style={styles.rSize}>{data.information?.pmcExpireDate}</Text>
            </View>
          </View>
        </View>
        <View style={styles.contentBox}>
          <View style={styles.viewFlex}>
            <View style={styles.flexLeft}>
              <Text style={styles.lSize}>缴费周期</Text>
            </View>
            <View style={[styles.flexRight]}>
              <Radios onGetVal={getRadioVal} defaultVal="1" list={periodList} dWidth={156}></Radios>
            </View>
          </View>
          <View style={styles.viewFlex}>
            <View style={styles.flexLeft}>
              <Text style={styles.lSize}>数量</Text>
            </View>
            <View style={styles.flexRight}>
              <Stepper onGetNum={getStepperNum} number={data.number} isInput={true}></Stepper>
            </View>
          </View>
          <View style={styles.viewFlex}>
            <View style={styles.flexLeft}>
              <Text style={styles.lSize}>价格</Text>
            </View>
            <View style={styles.flexRight}>
              <Text style={styles.rSize}>{data.information?.pmcPrice} 元 / m²</Text>
            </View>
          </View>
          <View style={[styles.viewFlex, { borderBottomWidth: 0 }]}>
            <View style={styles.flexLeft}>
              <Text style={styles.lSize}>折扣</Text>
            </View>
            <View style={styles.flexRight}>
              <Text style={styles.rSize}>{data.information?.pmcSingleDiscount! ? data.information?.pmcSingleDiscount! * 10 : 0}折</Text>
            </View>
          </View>
        </View>
        {data.activityText && (
          <View style={styles.contentBox}>
            <View style={styles.activeTitle}>
              <Text style={{ fontSize: 16 }}>优惠活动</Text>
            </View>
            <View style={styles.activeContent}>
              <Text style={{ fontSize: 14, color: '#000' }}>{data.activityText}</Text>
            </View>
          </View>
        )}
      </View>
      <View style={styles.submitView}>
        <View style={styles.sLeft}>
          <Text style={{ fontSize: 16 }}>合计：</Text>
          <Text style={{ fontSize: 18, color: CommonStyle.mainColor }}>￥{data.price}</Text>
        </View>
        <View style={styles.sRight}>
          <TouchableOpacity style={styles.submitBtn} onPress={handleSubmit}>
            <Text style={{ color: '#fff', fontWeight: 'bold' }}>提交订单</Text>
          </TouchableOpacity>
        </View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 20,
    height: '100%',
  },
  contentBox: {
    backgroundColor: 'white',
    width: '100%',
    minHeight: 100,
    borderRadius: 8,
    marginBottom: 30,
  },
  viewFlex: {
    flexDirection: 'row',
    minHeight: 44,
    padding: 16,
    borderBottomColor: '#eee',
    borderBottomWidth: 1,
    borderRadius: 8,
  },
  flexLeft: {
    flex: 1,
    justifyContent: 'center',
  },
  flexRight: {
    flex: 2,
    justifyContent: 'center',
    alignItems: 'flex-end',
  },
  lSize: {
    fontSize: 16,
  },
  rSize: {
    fontSize: 16,
    color: '#969799',
    textAlign: 'right',
  },
  submitView: {
    position: 'absolute',
    bottom: 0,
    width: '100%',
    height: 60,
    paddingTop: 10,
    paddingBottom: 10,
    paddingLeft: 20,
    paddingRight: 20,
    backgroundColor: '#fff',
    flexDirection: 'row',
  },
  sLeft: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  sRight: {
    flex: 1,
    alignItems: 'flex-end',
  },
  submitBtn: {
    width: 120,
    height: 40,
    borderRadius: 8,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: CommonStyle.mainColor,
  },
  activeTitle: {
    paddingTop: 10,
    paddingLeft: 10,
  },
  activeContent: {
    paddingLeft: 10,
    paddingRight: 10,
    paddingBottom: 10,
    paddingTop: 6,
  },
});

export default PropertyPayment;
